import { Form, Row, Col, Input, Button, Select } from 'antd'
import { connect } from 'dva'
import styles from './form.scss'
const FormItem = Form.Item
const formItemLayout = {
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 }
  },
  wrapperCol: {
    xs: { span: 10 },
    sm: { span: 20 }
  }
}
const Option = Select.Option

const InputList = ({
  formData,
  dispatch,
  form: {
    validateFields,
    getFieldDecorator
  }
}) => {
  const listData = formData.map((item, index) => {
    if (item.type === 'select') {
      var listOptions = item.option.map((item, index) => {
        console.log(item)
        return (
          <Option value={item} key={index}>{item}</Option>
        )
      })
    }
    return (
      <FormItem
      key={index}
      {...formItemLayout}
      className={styles.titleSize}
      label={item.title}
    >
      {item.type !== 'select'&&getFieldDecorator(item.value, {
        rules: [{
          required: true, message: `请输入${item.title}`,
        },{
          pattern:item.rule,
          message: `请输入正确的${item.title}`
        }],
        initialValue:item.init
      })(
        <Input/>
      )}
      { 
        item.type === 'select' && 
         getFieldDecorator(item.value, {
          rules: [{
            required: true, message: `请选择${item.title}`,
          },{
            pattern:item.rule,
            message: `请输入正确的${item.title}`
          }],
          initialValue:item.init
        })(
          <Select className={styles.selectSize}>
            {listOptions}
          </Select>
        )
      }
    </FormItem>
    )
   })
  const handleSubmit = (e) => {
    e.preventDefault()
    validateFields((err, values) => {
      if (!err) {
        console.log('表单的数据: ', values)
        dispatch({
          type: 'form/save',
          payload: values
        })
      } else {
        alert(`请完善信息`)
      }
    })
  }
  return (
    <Row className={styles.form}>
      <Col>
        <Form onSubmit={handleSubmit}>
        {listData}
        <FormItem className={styles.buttonSize}>
          <Button htmlType="submit" className={styles.cancel}>取消</Button>
          <Button type="primary" className={styles.ok} htmlType="submit">保存</Button>
        </FormItem>
        </Form>
      </Col>
    </Row>
  )
}
const WrappedInput = Form.create()(InputList)


export default connect((state) => state.form )(WrappedInput)

